import { ref, computed } from "vue";
import { ElMessageBox, ElMessage } from "element-plus";

/**
 * @description 表格多选数据操作
 * @param {String} rowKey 当表格可以多选时，所指定的 id
 * */
export const useSelection = (rowKey: string = "id", search, clearSelection) => {
  const isSelected = ref<boolean>(false);
  const selectedList = ref<{ [key: string]: any }[]>([]);

  // 当前选中的所有 ids 数组
  const selectedListIds = computed((): string[] => {
    let ids: string[] = [];
    selectedList.value.forEach(item => ids.push(item[rowKey]));
    return ids;
  });

  /**
   * @description 多选操作
   * @param {Array} rowArr 当前选择的所有数据
   * @return void
   */
  const selectionChange = (rowArr: { [key: string]: any }[]) => {
    rowArr.length ? (isSelected.value = true) : (isSelected.value = false);
    selectedList.value = rowArr;
  };

  // 批量删除
  const batchDelete = async (api, message, id, key = "ids") => {
    ElMessageBox.confirm(`是否${message}?`, "温馨提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
      draggable: true
    })
      .then(async () => {
        // let data = {}
        // data[key] = id ? id : selectedListIds.value.join(",")
        // const res = await api(data);
        // if (!res) {
        //   return ElMessage({
        //     type: "success",
        //     message: "删除失败!"
        //   });
        // }
        // ElMessage({
        //   type: "success",
        //   message: "删除成功!"
        // });
        // search();
        // clearSelection();

        ElMessage({
          type: "success",
          message: "删除成功!" + selectedListIds.value.join(",")
        });
        search();
        clearSelection();
      })
      .catch(() => {
        // cancel operation
      });
  };

  return {
    isSelected,
    selectedList,
    selectedListIds,
    selectionChange,
    batchDelete
  };
};
